/**
 * Created by zxr on 16/6/1.
 */
var mysql = require('../mysql');
var uglobal = require('../global');
//var Q = require('Q');
//function getUserByUserName(userName) {
//    mysql.connect();
//    var detered = Q.defer();
//    var sql = "SELECT * FROM q_user WHERE uname = ?";
//    mysql.query(sql, [userName], defered.makeNodeResolver());
//    mysql.close();
//    return detered.promise;
//
//}


exports.checkUser = function(userName,password,calledBackevent){
    mysql.connect();
    var sql = "select * from q_user where uname = ?";
    mysql.query(sql,[userName],function(err,rows,fileds){
        if (rows && rows.length > 0){
            var salt = rows[0].salt;
            var newpassword ="";
            if ( salt){
                 newpassword = uglobal.getSignPassword(password,salt);
            } else {
                newpassword = password;
            }
            if(newpassword == rows[0].password){
                calledBackevent.emit("loginok",{uid:rows[0].uid,uname:rows[0].uname});
            } else {
             calledBackevent.emit("loginfail");
            }
        } else {
            calledBackevent.emit("loginfail");
        }
    });
};
//登录？
//exports.checkUser = function (userName, password, callbackevent) {
//    mysql.connect();
//    Q.all([getUserByUserName(userName)]).then(function (results) {
//        if (results[0][0] && results[0][0].length > 0) {
//            var salt = results[0][0][0].salt;
//            var user = uglobal.checkLogin(req);
//            var newpassword = "";
//
//            if (salt != '') {
//                newpassword = uglobal.getSignPassword(password, salt);
//            } else {
//                newpassword = password;
//            }
//            if (results[0][0][0].password == newpassword) {
//                callbackevent.emit('loginok',{uid:results[0][0][0].uid,unam:results[0][0][0].uname});
//            } else {
//                callbackevent.emit('loginfail');
//            }
//
//        } else{
//            callbackevent.emit('loginfail');
//        }
//    })
//};


exports.getTUserByUids = function (uids, teachers, mysql, callbackevents) {//callbackevents 添加事件
    //mysql.connect();
    var usql = "select * from q_user where uid in(" + uids.join(",") + ")";
    mysql.query(usql, function (uerr, urows, ufileds) {
        if (urows && urows.length > 0) {
            var users = {};
            for (var j = 0; j < urows.length; j++) {
                users[urows[j].uid] = urows[j].uname;
            }
            for (x in teachers) {
                teachers[x]['uname'] = users[teachers[x]['uid']];
            }
            callbackevents.emit('uteacherlist', {teachers: teachers});//成功时发送事件，和携带数据发送出去
        } else {
            callbackevents.emit("nouteacher");//失败时 发送事件noteacherlist
        }

    });
    //mysql.close();
}